/*
 */

package com.meida.module.virbox.provider.licenseProvider;



import com.meida.common.utils.JsonUtils;
import com.meida.module.virbox.provider.entity.AuthToken;
import org.springframework.security.access.method.P;

import javax.crypto.Cipher;
import java.io.*;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class License {

    private static final String KEY_ALGORITHM = "RSA";

    private static final String PUBLIC_KEY_STR = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArGW/smQnPNdfBNskOAXmwnPSOweNyLdFSWGdUAOY1zl0U/OKe2usa3sgiumG0KlvIJzgclQK4r+4QyNTV0kofdXROuFVtKvumIiMDxSNjNzzbCi592ikPbK2JtpMj4JX3qE+Fpt5jqDwKTjXza0vTbtxdObubVISWXt5k+MRjWyGWUy1e3l0j5LLO2wdGtZJAu6nVs/S2pTcVNIhAAPNUcOxuiXbSIVSpJpqaw053JsST5/elUBPZ2H1MECKv5JRw1tGi/FiSuCNAiCUBJrpeL01k3UnNPTYeoiS1R9h+5+DpciohPseKBC6SWXrx029HKaefq4oaC7AExLIHy780QIDAQAB";
public static AuthToken loadLicense(InputStream inputStream) {
        ByteArrayOutputStream outStream = null;
        try {
            outStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = -1;
            while((len=inputStream.read(buffer))!=-1){
                outStream.write(buffer,0,len);
            }
            byte[] data = decryptByPublicKey(Base64.getDecoder().decode(outStream.toByteArray()), Base64.getDecoder().decode(PUBLIC_KEY_STR));
            return JsonUtils.jsonToBean(new String(data,"UTF8"),AuthToken.class);
        } catch (LicenseException e) {
            throw e;
        } catch (Exception e) {
            throw new LicenseException("load license exception", e);
        } finally {
            if (outStream != null) {
                try {
                    outStream.close();
                    outStream = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static AuthToken loadLicense(File file) {
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(file);
            return loadLicense(fileInputStream);
        } catch (Exception e) {
            throw new LicenseException("load license exception", e);
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                    fileInputStream = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 使用公钥进行解密
     *
     * @param data
     * @param publicKey
     * @return
     */
    private  static byte[] decryptByPublicKey(byte[] data, byte[] publicKey) {
        try {
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            X509EncodedKeySpec encodedKeySpec = new X509EncodedKeySpec(publicKey);
            PublicKey pubKey = keyFactory.generatePublic(encodedKeySpec);
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.DECRYPT_MODE, pubKey);
            return cipher.doFinal(data);
        } catch (Exception e) {
            throw new LicenseException("decrypt exception", e);
        }
    }

//    private static String encodeByPrivateKey(String data){
//        try {
//            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(PRIVATE_KEY_STR));
//            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
//            PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
//            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
//            cipher.init(Cipher.ENCRYPT_MODE, privateKey);
//            return Base64.getEncoder().encodeToString(cipher.doFinal(data.getBytes(), 0, data.getBytes().length));
//        } catch (Exception e) {
//            throw new LicenseException("encrypt exception", e);
//        }
//    }

    public static void main(String[] args) {
       //System.out.println(encodeByPrivateKey("{\"code\":\"1234567890\",\"org\":\"芸芸创新（北京）科技有限公司\",\"qzCount\":5,\"userCount\":0,\"categoryCount\":0,\"categoryActCount\":0,\"companyCount\":0,\"authTime\":0,\"onlineCount\":8,\"tokenType\":0}"));
        AuthToken token = License.loadLicense(new File("C:\\Users\\Administrator\\Desktop\\新建文件夹\\cert.lic"));
        System.out.println(token);
    }
}
